
package com.kingdee.pda.plugins.http.common.coreprogress;


import com.kingdee.pda.util.StringUtils;
import com.kingdee.pda.util.FileUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.MediaType;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source;


/**
 * 包装的响体，处理进度
 *
 * @author ZhuHuaHua
 * @date 2016/10/23 18:12
 */
public class ProgressResponseBody extends ResponseBody {
    //实际的待包装响应体
    private final ResponseBody responseBody;
    //进度回调接口
    private final ProgressListener progressListener;
    //包装完成的BufferedSource
    private BufferedSource bufferedSource;
    //本地的url
    private  String  localUrl;
    /**
     * 构造函数，赋值
     * @param responseBody 待包装的响应体
     * @param progressListener 回调接口
     */
    public ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener,String url) {
        this.responseBody = responseBody;
        this.progressListener = progressListener;
        this.localUrl=url;
    }


    /**
     * 重写调用实际的响应体的contentType
     * @return MediaType
     */
    @Override public MediaType contentType() {
        return responseBody.contentType();
    }

    /**
     * 重写调用实际的响应体的contentLength
     * @return contentLength
     * @throws IOException 异常
     */
    @Override public long contentLength() {
        return responseBody.contentLength();
    }

    /**
     * 重写进行包装source
     * @return BufferedSource
     * @throws IOException 异常
     */
    @Override
    public BufferedSource source() {
        if (bufferedSource == null) {
            //包装
            bufferedSource = Okio.buffer(source(responseBody.source(),localUrl));
        }
        return bufferedSource;
    }

    /**
     * 读取，回调进度接口
     * @param source Source
     * @return Source
     */
    private Source source(Source source,String localUrl) {
        return new MyForwardingSource(source,localUrl);
    }
    class  MyForwardingSource extends ForwardingSource {
        //当前读取字节数
        long totalBytesRead = 0L;
        private  File file;
        private String localUrl;
        public MyForwardingSource(Source delegate,String url) {
            super(delegate);
            this.localUrl=url;
            if (FileUtils.isFileExist(localUrl)){
                FileUtils.deleteFile(localUrl);
            }
            if (!StringUtils.isEmpty(url)){
                file = new File(localUrl);
            }else {
                //TODO 待处理
            }

        }

        @Override
        public long read(Buffer sink, long byteCount) throws IOException {
            long bytesRead = super.read(sink, byteCount);

            //增加当前读取的字节数，如果读取完成了bytesRead会返回-1
            totalBytesRead += bytesRead != -1 ? bytesRead : 0;
            //回调，如果contentLength()不知道长度，会返回-1
            if (progressListener!=null) {
                progressListener.onProgress(totalBytesRead, responseBody.contentLength(), bytesRead == -1);
            }
            //写入IO流
            write(sink);
            return bytesRead;
        }

        public void write(Buffer sink){
            InputStream is =  sink.inputStream();
            byte[] buf = new byte[2048];
            int len ;
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(file,true);
                while ((len = is.read(buf)) != -1) {
                    fos.write(buf, 0, len);
                }
                fos.flush();
            } catch (Exception e) {
            } finally {
                try {
                    if (is != null)
                        is.close();
                } catch (IOException e) {
                }
                try {
                    if (fos != null)
                        fos.close();
                } catch (IOException e) {
                }
            }
        }
    }


}